import { Line } from '@ant-design/charts';
import { AliwangwangFilled, ThunderboltFilled } from '@ant-design/icons';
import { ProCard, StatisticCard } from '@ant-design/pro-components';
import { Card, Col, Divider, Row, Statistic, DatePicker  } from 'antd';
import RcResizeObserver from 'rc-resize-observer';
import { useState, useEffect } from 'react';
import moment from 'moment';
import dayjs from 'dayjs';
import { userCountsGet, shortChainCountGet, userRegisterCountPost,shortChainVisitGet } from '@/services/backend/welcomeController';
import { SUCCESS_CODE } from '@/constants/index';


export default () => {
  const { RangePicker } = DatePicker;
  const [responsive, setResponsive] = useState<boolean>(false);
  const [count, setCount] = useState({//存储用户数，短链数，流量变化
    registerCount:[],
    userCounts:0,
    shortChainCount:0,
    shortChainVisit:0,
  });
  const [timeRange, setTimeRange] = useState<API.UserRegisterCount>({});// 存储时间范围的开始和结束日期
  
  //设置默认时间范围
  useEffect(() => {
    init();
  }, []);

  //初始化数据
  const init = async () => {
      const defaultStartDate = moment().subtract(7, 'days').toDate();
      const defaultEndDate = moment().toDate();
      const range: API.UserRegisterCount = {
          startDate: defaultStartDate.toISOString().split('T')[0],
          endDate: defaultEndDate.toISOString().split('T')[0],
      }
      setTimeRange(range);
      const res1 = await userCountsGet();
      const res2 = await shortChainCountGet();
      const res3 = await userRegisterCountPost(range);
      const res4 = await shortChainVisitGet();
      if (res1.code === SUCCESS_CODE && res2.code === SUCCESS_CODE && res4.code === SUCCESS_CODE){
        setCount((prevState:any) => {
          const newCount = {
            ...prevState,
            userCounts: res1.data,
            shortChainCount: res2.data,
            registerCount: res3.data,
            shortChainVisit: res4.data,
          };
          return newCount;
        });
      }
  }
  const userRegisterRange = async (range:any) => {
    const res = await userRegisterCountPost(range);
    if (res.code === SUCCESS_CODE){
      setCount((prevState:any) => {
        const newCount = {
          ...prevState,
          registerCount: res.data,
        };
        console.log(newCount);
        return newCount;
      });
    }
  };
  //时间范围修改
  const handleTimeChange = async (dates) => {
    const [start, end] = dates;
  // 将 moment 对象转换为 'YYYY-MM-DD' 格式的字符串
    const startDate = start ? start.format('YYYY-MM-DD') : undefined;
    const endDate = end ? end.format('YYYY-MM-DD') : undefined;
    // 创建 UserRegisterCount 类型的对象
    const range: API.UserRegisterCount = {
      startDate,
      endDate,
    };
    setTimeRange(range);
    userRegisterRange(range);
  };
  
  // 禁用今天的日期之后的所有日期
  const disabledDate = (current:object) => {
     // 获取今天的日期，然后添加一天得到明天的日期
    const tomorrow = moment().add(1, 'days');
    // 禁用明天及之后的所有日期
    return current && current.isSameOrAfter(tomorrow, 'day');
  };
  //数据表格配置
  const config = {
    data:count.registerCount,
    height: 400,
    xField: 'date',
    yField: 'count',
    point: {
      size: 5,
      shape: 'diamond',
    },
  };
  
  // @ts-ignore
  return (
    <RcResizeObserver
      key="resize-observer"
      onResize={(offset) => {
        setResponsive(offset.width < 596);
      }}
    >
      <Row gutter={16}>
        <Col span={8}>
          <Card bordered={false}>
            <Statistic
              title="用户数"
              value={count.userCounts}
              precision={2}
              valueStyle={{ color: '#3f8600' }}
              prefix={<AliwangwangFilled />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card bordered={false}>
            <Statistic
              title="已生成短链数"
              value={count.shortChainCount}
              precision={2}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ThunderboltFilled />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card bordered={false}>
            <Statistic
              title="短链点击总数"
              value={count.shortChainVisit}
              precision={2}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ThunderboltFilled />}
            />
          </Card>
        </Col>
      </Row>
      <Divider type={'horizontal'} />
      <ProCard
        title="数据概览"
        extra={
        <RangePicker
          defaultValue={[dayjs(timeRange.startDate), dayjs(timeRange.endDate)]}
          value={[dayjs(timeRange.startDate), dayjs(timeRange.endDate)]}
          onChange={handleTimeChange}
          disabledDate={disabledDate}
        />
      }
        split={responsive ? 'horizontal' : 'vertical'}
        headerBordered
        bordered
      > 
        <ProCard split="horizontal">
          <StatisticCard title="流量走势" chart={<Line {...config} />} />
        </ProCard>
      </ProCard>
    </RcResizeObserver>
  );
};
